package com.fxsh168.server.activity;

import android.Manifest;
import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fxsh168.server.base.CheckPermissionsActivity;
import com.fxsh168.server.entitys.UpdateVersonEntity;
import com.fxsh168.server.fragments.MapFragment;
import com.fxsh168.server.fragments.MyOrderFragment;
import com.fxsh168.server.fragments.PersonFragment;
import com.fxsh168.server.R;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.upapk.Updater;
import com.fxsh168.server.upapk.UpdaterConfig;
import com.fxsh168.server.utils.upapp.UpdateApp;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;


public class MainActivity extends CheckPermissionsActivity implements View.OnClickListener {
    private FragmentManager mFragmentManager;
    private MyOrderFragment mMyOrderFragment;
    private PersonFragment mPersonFragment;
    private MapFragment mMapFragmnt;
    private LinearLayout mMapLinearLayout;
    private ImageView mMap, mMyorder, mPerson;
    private LinearLayout mMyorderLinearLayout, mPersonLinearLayout;
    private TextView mMapFont, mMyOderFont, mPersonFont;
    String mPhone, token;
    private AlertDialog dialogPerMsgup;
    private TextView msgContentViewup;
    //    权限
    protected String[] needContactsPermissions = {
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentManager = getSupportFragmentManager();
        initViews();
        setTabSelection(0);
        requestPermission();
        initVersonUpdatetaxi();              //判断是否有版本更新
    }

    private void initVersonUpdatetaxi() {
//        ToUpdateUI.shareAppShop(this,this.getPackageName());
        /*did 设备号
        version_id 版本号
        version_mini 小版本号
        app_id  app类型 5为安卓司机 6位安卓用户*/
//        UUID deviceUid = new DeviceUuidFactory(AboutUsActivity.this).getDeviceUuid();
//        String deviceUuid = deviceUid.toString().trim();
        final String versionName = UpdateApp.getVersionName(MainActivity.this);
        OkHttpUtils.post().addParams("version_id", versionName).addParams("app_id", 5 + "")
                .url(Constant.APPUPDATECHECKPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    UpdateVersonEntity updateVersonEntity = new Gson().fromJson(response, UpdateVersonEntity.class);
                    String code = updateVersonEntity.getCode().trim();
                    if (code.equals(200 + "")) {
                        Log.e("tagup", "版本信息获取成功" + response);
                        List<UpdateVersonEntity.DataBean> dataup = updateVersonEntity.getData();
                        if (dataup.size() > 0) {
                            String Upgrade_point = dataup.get(0).getUpgrade_point().trim();
                            int is_upload = dataup.get(0).getIs_upload();
                            final String apk_url = dataup.get(0).getApk_url().trim();
                            String version_id = dataup.get(0).getVersion_id();
//                            if (is_upload == 0) {
//                                Log.e("提醒", "版本号相同，无需下载!");
//                            } else
                            if (Double.parseDouble(versionName) < Double.parseDouble(version_id)) {
                                Log.e("提醒", "有版本更新，下载!");
                                //用自定义dialog
                                AlertDialog.Builder builderup = new AlertDialog.Builder(MainActivity.this);
                                View viewup = LayoutInflater.from(MainActivity.this).inflate(R.layout.appupdatemsgdialog_layout, null);//获取布局
                                builderup.setView(viewup);
                                TextView caceup = (TextView) viewup.findViewById(R.id.btnCancelup); //取消
                                caceup.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialogPerMsgup.dismiss();
                                        finish();
                                    }
                                });
                                msgContentViewup = (TextView) viewup.findViewById(R.id.msgContentViewup);
                                msgContentViewup.setText(Upgrade_point);
                                TextView btnOkup = (TextView) viewup.findViewById(R.id.btnOKPerMsgup);//确定
                                btnOkup.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        download(apk_url);
                                        //让对话框消失
                                        dialogPerMsgup.dismiss();
                                    }
                                });

                                dialogPerMsgup = builderup.create();
                                dialogPerMsgup.setCanceledOnTouchOutside(true);
                                dialogPerMsgup.show();

                                WindowManager m = MainActivity.this.getWindowManager();
                                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                                WindowManager.LayoutParams p = dialogPerMsgup.getWindow().getAttributes();// 获取对话框当前的参数值
                                p.height = (int) (d.getHeight() * 0.215); // 高度设置为屏幕的0.6
                                p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.95
                                dialogPerMsgup.getWindow().setBackgroundDrawableResource(R.drawable.shapeindexexit);
                                dialogPerMsgup.getWindow().setAttributes(p);
                            }
//                            else if (is_upload == 2) {
//                                Log.e("提醒", "有版本更新，强制下载!");
//                            } else {
//                                Log.e("无", "无");
//                            }
                        }
                    } else if (code.equals(402 + "")) {
                        Log.e("tag", "app_id不存在");
                    } else if (code.equals(403 + "")) {
                        Log.e("tag", "没有该权限");
                    } else if (code.equals(400 + "")) {
                        Log.e("tag", "版本信息获取失败");
                    }
                }
            }
        });
    }

    public void download(String url) {
        UpdaterConfig config = new UpdaterConfig.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setDescription(getString(R.string.system_download_description))
                .setFileUrl(url)
                .setCanMediaScanner(true)
                .build();
        Updater.get().showLog(true).download(config);
    }

    private void requestPermission() {
        if (!mayRequestPermission(needContactsPermissions)) {
            return;
        }
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            showToast("权限申请成功");
        } else {
            showToast("请前往设置中心允许定位权限");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.map:
                setTabSelection(0);
                break;
            case R.id.myOder:
                setTabSelection(1);
                break;
            case R.id.person:
                setTabSelection(2);
                break;
            default:
                break;
        }

    }

    private void initViews() {
        mMapLinearLayout = (LinearLayout) findViewById(R.id.map);
        mMyorderLinearLayout = (LinearLayout) findViewById(R.id.myOder);
        mPersonLinearLayout = (LinearLayout) findViewById(R.id.person);
        mMapLinearLayout.setOnClickListener(this);
        mMyorderLinearLayout.setOnClickListener(this);
        mPersonLinearLayout.setOnClickListener(this);

        mMap = (ImageView) findViewById(R.id.mapImg);
        mMyorder = (ImageView) findViewById(R.id.myorderImg);
        mPerson = (ImageView) findViewById(R.id.personImg);

        mMapFont = (TextView) findViewById(R.id.map_font);
        mMyOderFont = (TextView) findViewById(R.id.myOder_font);
        mPersonFont = (TextView) findViewById(R.id.person_font);
    }

    private void setTabSelection(int index) {
        clearSelection();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                mMap.setImageResource(R.mipmap.ditu);
                mMapFont.setTextColor(Color.rgb(251, 72, 24));
                if (mMapFragmnt == null) {
                    mMapFragmnt = new MapFragment();
                    transaction.add(R.id.main_framlayout, mMapFragmnt);
                } else {
                    transaction.show(mMapFragmnt);
                }
                break;
            case 1:
                mMyorder.setImageResource(R.mipmap.dingdan);
                mMyOderFont.setTextColor(Color.rgb(251, 72, 24));
                if (mMyOrderFragment == null) {
                    mMyOrderFragment = new MyOrderFragment();
                    transaction.add(R.id.main_framlayout, mMyOrderFragment);
                } else {
                    transaction.show(mMyOrderFragment);
                }
                break;
            case 2:
            default:
                mPerson.setImageResource(R.mipmap.wode);
                mPersonFont.setTextColor(Color.rgb(251, 72, 24));
                if (mPersonFragment == null) {
                    mPersonFragment = new PersonFragment();
                    transaction.add(R.id.main_framlayout, mPersonFragment);
                } else {
                    transaction.show(mPersonFragment);
                }
                break;
        }
        transaction.commit();
    }

    /*
    影藏后面的fragment
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mMapFragmnt != null) {
            transaction.hide(mMapFragmnt);
        }
        if (mMyOrderFragment != null) {
            transaction.hide(mMyOrderFragment);
        }
        if (mPersonFragment != null) {
            transaction.hide(mPersonFragment);
        }
    }

    /**
     * 清除掉所有的选中状态。
     */
    private void clearSelection() {
        mMap.setImageResource(R.mipmap.map);
        mMyorder.setImageResource(R.mipmap.order);
        mPerson.setImageResource(R.mipmap.my_icon);

        mMapFont.setTextColor(Color.argb(255, 166, 166, 166));
        mMyOderFont.setTextColor(Color.argb(255, 166, 166, 166));
        mPersonFont.setTextColor(Color.argb(255, 166, 166, 166));
    }


}
